<template>
	<layout :footerVisible="true">
		<view class="h-fill">
			<u-navbar :title="shop.name || '未知门店'" titleColor="#fff" backIconColor="#fff" :background="navBg" :borderBottom="false"></u-navbar>
			<view class="board">
				<view class="rect-1"></view>
				<view class="rect-2"></view>
				<image src="static/img/ic_beijing_zhuangshi@2x.png" mode="aspectFit"></image>
				<view class="rent-info uni-flex uni-column pad align-center justify-center">
					<text v-if="selectedGoods" class="uni-text-big uni-bold">租借{{selectedGoods.name}}</text>
					<text v-if="selectedGoods">押金：￥{{selectedGoods ? selectedGoods.pledge / 100 : '0'}}</text>
					<text v-else>未选择物品</text>
				</view>
			</view>
			<view class="rent-goods-list" :style="{top: listTop + 'px'}">
				<scroll-view class="v-fill" scroll-y>
					<uni-grid @change="handleChange" :column="4" :square="false" :showBorder="false" :highlight="false">
						<uni-grid-item :index="idx" v-for="(item, idx) in rentGoodsList" :key="item.id">
							<view class="rent-goods-item" :class="{'rent-goods-item__active': item.selected}">{{item.name}}</view>
						</uni-grid-item>
					</uni-grid>
				</scroll-view>
			</view>
		</view>
		<view slot="footer" class="v-fill">
			<view class="buy-action v-fill">
				<view class="uni-flex v-fill align-center l-pad">
					<text>押金：</text>
					<text class="text-cash uni-flex-extend">￥{{totalAmount}}</text>
					<view class="r-mg-2">
						<u-number-box v-model="count" :min="1"></u-number-box>
					</view>
					<view class="btn-pay v-fill h-box justify-center" @click="handlePay">支付</view>
				</view>
			</view>
		</view>
	</layout>
</template>

<script>
	import {
		
	} from "../api/user.js";
	import {
		genRentOrder,
		genPayInfo,
		getOrderDetail
	} from "../api/platform/order.js";
	import {
		mapState, mapMutations
	} from "vuex"
	export default {
		data() {
			return {
				navBg: {
					'background-image': 'linear-gradient(to right, #434AD8, #8E77F5)'
				},
				rentGoodsList: [],
				count: 1,
				listTop: 0,
				order: null,
				orderPayInfo: null,
				busy: false,
				hasPayed: false,
				shop: {}
			};
		},
		computed: {
			...mapState(["userInfo"]),
			selectedGoods() {
				let selected = this.rentGoodsList.filter(item => {
					return item.selected
				})
				return selected.length ? selected[0] : null
			},
			totalAmount() {
				if (!this.selectedGoods) {
					return 0;
				}
				return this.selectedGoods.pledge / 100 * this.count;
			}
		},
		watch: {
			userInfo(newVal) {
				if (newVal.id) {
					this.loadData();
				}
			}
		},
		async onLoad(option) {
			if (option.q) {
				//通过小程序自定义码进入的
				let url = decodeURIComponent(option.q);
				let matches = /shopId=([a-z]|[0-9]){24,32}/.exec(url);
				if (matches && matches.length) {
					let shopId = matches[0].split("=")[1];
					console.log("shopId", shopId);
					this.shop._id = shopId;
				}
			} else if (option.scene) {
				//通过小程序二维码进入的
				let params = decodeURI(option.scene);
				let matches = /shopId=([a-z]|[0-9]){24,32}/.exec(params);
				if (matches && matches.length) {
					let shopId = matches[0].split("=")[1];
					console.log("shopId", shopId);
					this.shop._id = shopId;
				}
			} else {
				if (option.shopId) {
					this.shop._id = option.shopId;
				}
			}
		},
		onReady() {
			this.loadData()
		},
		created() {
			let sysInfo = uni.getSystemInfoSync();
			var navHeight = 44;
			// #ifdef MP
			let rect = uni.getMenuButtonBoundingClientRect();
			navHeight = (rect.top - sysInfo.statusBarHeight) * 2 + rect.height;
			// #endif
			this.listTop = sysInfo.statusBarHeight + navHeight + uni.upx2px(30 + 773 + 70);
		},
		methods: {
			async finishPay(order) {
				try {
					order = await getOrderDetail({
						id: order._id
					})
					if (order.status === 3) {
						this.hasPayed = true
						return true
					}
				} catch (e) {
					console.error(e)
					uni.showModal({
						content: '查询支付状态遇到错误！',
						cancelText: '联系客服',
						confirmText: '重试',
						success: (res) => {
							if (res.confirm) {
								this.finishPay(order)
							} else {
								this.$copy("i3d008", () => {
									uni.showModal({
										content: '客服微信已复制，请添加客服好友',
										showCancel: false,
										confirmText: '朕知道了'
									})
								})
							}
						}
					})
				}
			},
			async handlePay() {
				if (!this.selectedGoods) {
					this.$showError("请选择租借的物品")
					return
				}
				uni.showLoading({
					mask: true
				})
				try {
					let order = await genRentOrder({
						count: this.count,
						goodsId: this.selectedGoods._id,
						showLoading: false
					})
					let orderPayInfo = await genPayInfo({
						orderId: order._id,
						showLoading: false
					});
					uni.showLoading({
						mask: true,
						title: '检测支付环境'
					})
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: orderPayInfo.timeStamp,
						nonceStr: orderPayInfo.nonceStr,
						package: orderPayInfo.package,
						signType: orderPayInfo.signType,
						paySign: orderPayInfo.paySign,
						success: async (res) => {
							console.log('支付成功', res)
							uni.hideLoading()
							let success = await this.finishPay(order)
							if (success) {
								uni.showModal({
									content: '押金已支付，请去前台领取物品',
									showCancel: false,
									confirmText: '朕知道了'
								})
							}
						},
						fail: (err) => {
							console.log('用户取消支付', err)
							uni.hideLoading()
						}
					})
				} catch (e) {
					console.error(e)
					uni.hideLoading()
				}
			},
			askRetryPay() {
				uni.showModal({
					title: "查询支付状态遇到错误，是否重试？",
					cancelText: "稍后查看",
					confirmText: "重试",
					success: (res) => {
						if (res.confirm) {
							this.finishPay();
						} else {
							uni.navigateBack();
						}
					}
				})
			},
			handleChange(e) {
				if (this.rentGoodsList[e.detail.index].selected) {
					this.rentGoodsList[e.detail.index].selected = false
				} else {
					this.rentGoodsList.forEach(item => {
						item.selected = false
					})
					this.rentGoodsList[e.detail.index].selected = true
				}
			},
			async loadData() {
				uni.showLoading({
					mask: true
				})
				try {
					this.shop = await this.$dbHelper.getById("t3ds-store", this.shop._id, {
						showLoading: false
					})
					if (!this.shop) {
						uni.showModal({
							content: '未获取到门店信息',
							cancelText: '取消',
							confirmText: '联系客服',
							success: (res) => {
								if (res.confirm) {
									this.$copy("i3d008", () => {
										uni.showModal({
											content: '客服微信已复制，请添加客服好友',
											showCancel: false,
											confirmText: '朕知道了'
										})
									})
								} else {
									let pages = getCurrentPages();
									if (pages.length === 1) {
										uni.reLaunch({
											url: "/pages/platform/goods-list"
										})
									} else {
										uni.navigateBack();
									}
								}
							}
						})
					}
					let list = await this.$dbHelper.getList("t3ds-goods-rent", {
						showLoading: false,
						where: `storeId == '${this.shop._id}' && enable == true`
					})
					list.forEach(item => {
						item.selected = false
					})
					this.rentGoodsList = list
					uni.hideLoading()
				} catch (e) {
					this.$log("加载租借物品列表遇到错误", e);
				}
			}
		}
	}
</script>
<style lang="scss">
	page {
		background-image: linear-gradient(to right, #434AD8, #8E77F5);
	}
</style>
<style lang="scss" scoped>
	.board {
		position: absolute;
		left: 0;
		right: 0;

		image {
			position: relative;
			top: 30rpx;
			left: 50%;
			transform: translateX(-50%);
			width: 680rpx;
			height: 773rpx;
			vertical-align: middle;
		}

		.rent-info {
			position: absolute;
			top: 170rpx;
			left: 50%;
			transform: translateX(-50%);
			width: 339rpx;
			height: 175rpx;
		}

		.rect-1 {
			position: absolute;
			background-color: rgba($color: #FFFFFF, $alpha: 0.6);
			border-radius: 30rpx;
			left: 50%;
			transform: translate(-50%, 0);
			top: 140rpx;
			width: 612rpx;
			height: 696rpx;
		}

		.rect-2 {
			position: absolute;
			background-color: rgba($color: #FFFFFF, $alpha: 0.2);
			border-radius: 30rpx;
			top: 180rpx;
			width: 551rpx;
			height: 690rpx;
			left: 50%;
			transform: translate(-50%, 0);
		}
	}

	.rent-goods-list {
		position: absolute;
		// top: 90rpx;
		// #ifdef H5
		bottom: 108rpx;
		// #endif
		// #ifndef H5
		bottom: calc(108rpx + constant(safe-area-inset-bottom));
		bottom: calc(108rpx + env(safe-area-inset-bottom));
		// #endif
		right: 0;
		left: 0;

		scroll-view {
			padding: 0 35rpx;
		}
	}

	.rent-goods-item {
		height: 60rpx;
		line-height: 60rpx;
		background-color: rgba($color: #FFFFFF, $alpha: 0.4);
		width: 80%;
		border-radius: 60rpx;
		text-align: center;
		color: rgba($color: #FFFFFF, $alpha: 0.5);
		margin: 20rpx 0;
	}

	.rent-goods-item__active {
		background-color: #FE8917;
		color: #FFFFFF;
	}

	.buy-action {
		.text-cash {
			color: $bg-red;
		}

		.btn-pay {
			background-color: $bg-red;
			width: 200rpx;
			color: #FFFFFF;
			text-align: center;
		}
	}
</style>
